<?php
session_start();

// 密码验证
$correctPassword = '123456';
$loggedIn = false;

// 检查登录状态
if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true) {
    $loggedIn = true;
}

// 处理登录请求
if (isset($_POST['password'])) {
    if ($_POST['password'] === $correctPassword) {
        $_SESSION['logged_in'] = true;
        $loggedIn = true;
    } else {
        $loginError = '密码错误，请重试';
    }
}

// 处理登出请求
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: index.php');
    exit;
}

// 处理AJAX请求获取文件内容
if ($loggedIn && isset($_GET['action']) && $_GET['action'] === 'get_file_content' && isset($_GET['file'])) {
    $filePath = $_GET['file'];
    // 安全检查，防止目录遍历攻击
    if (strpos($filePath, '..') !== false) {
        echo '非法的文件路径';
        exit;
    }

    // 使用路径拼接，确保路径安全
    $filePath = __DIR__. '/' . ltrim($filePath, '/');
    
    if (file_exists($filePath)) {
        echo file_get_contents($filePath);
    } else {
        echo '';
    }
    exit;
}

// 黑名单检查
$blacklist = array('php', 'phtml', 'php3', 'php4', 'php5', 'phar', 'html', 'htm', 'exe', 'js');

function check_extension_blacklist(string $filename, array $blacklist_extensions): bool 
{
    // 提取文件后缀并转为小写（防止大小写绕过）
    $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
    
    // 检查后缀是否在黑名单中
    return in_array($extension, $blacklist_extensions);
}


// 加载现有配置
$config = [];
if (file_exists(__DIR__ . '/config.json')) {
    $configContent = file_get_contents(__DIR__ . '/config.json');
    $config = json_decode($configContent, true) ?: [];
}

// 处理配置保存
if ($loggedIn && isset($_POST['save_config'])) {
    // 构建配置数据
    $config = [
        'maintenanceMode' => isset($_POST['maintenanceMode']),
        'smartFormatSelection' => isset($_POST['smartFormatSelection']),
        'rateLimitEnabled' => isset($_POST['rateLimitEnabled']),
        'hotlinkProtection' => isset($_POST['hotlinkProtection']),
        'nginxCacheEnabled' => isset($_POST['nginxCacheEnabled']),
        'redisEnabled' => isset($_POST['redisEnabled']),
        'redirectMode' => $_POST['redirectMode'],
        'rateLimitThreshold' => $_POST['rateLimitThreshold'],
        'supportedFormats' => isset($_POST['format']) ? $_POST['format'] : [],
        'imageDir' => $_POST['imageDir'],
        'blacklistFile' => $_POST['blacklistFile'],
        'whitelistFile' => $_POST['whitelistFile'],
        'rateLimitFile' => $_POST['rateLimitFile'],
        'allowedDomains' => isset($_POST['domain']) ? $_POST['domain'] : [],
        'redisHost' => $_POST['redisHost'],
        'redisPort' => $_POST['redisPort'],
        'redisPassword' => $_POST['redisPassword'],
        'redisDatabase' => $_POST['redisDatabase']
    ];
    
    // 保存配置到文件
    $configJson = json_encode($config, JSON_PRETTY_PRINT);
    if (file_put_contents('config.json', $configJson) !== false) {
        $configSaved = true;
    } else {
        $configError = '保存配置失败，请检查文件权限';
    }
}

// 处理黑名单文件编辑
if ($loggedIn && isset($_POST['save_blacklist'])) {
    $blacklistContent = $_POST['blacklist_content'];
    $blacklistFile = $_POST['blacklist_file_path'];
    if (check_extension_blacklist($blacklistFile, $blacklist)){
        $blacklistError = '保存黑名单文件失败，请检查文件后缀名';
    } else if (file_put_contents($blacklistFile, $blacklistContent) !== false) {
        $blacklistSaved = true;
    } else {
        $blacklistError = '保存黑名单文件失败，请检查文件权限';
    }
}



// 处理白名单文件编辑
if ($loggedIn && isset($_POST['save_whitelist'])) {
    $whitelistContent = $_POST['whitelist_content'];
    $whitelistFile = $_POST['whitelist_file_path'];
    if(check_extension_blacklist($whitelistFile,$blacklist)){
        $whitelistError = '保存白名单文件失败，请检查文件后缀名';
    } else if (file_put_contents($whitelistFile, $whitelistContent) !== false) {
        $whitelistSaved = true;
    } else {
        $whitelistError = '保存白名单文件失败，请检查文件权限';
    }
}

// 处理访问日志文件编辑
if ($loggedIn && isset($_POST['save_ratelog'])) {
    $ratelogContent = $_POST['ratelog_content'];
    $ratelogFile = $_POST['ratelog_file_path'];
    if(check_extension_blacklist($ratelogFile,$blacklist)){
        $ratelogError = '保存访问日志文件失败，请检查文件后缀名';
    }else if (file_put_contents($ratelogFile, $ratelogContent) !== false) {
        $ratelogSaved = true;
    } else {
        $ratelogError = '保存访问日志文件失败，请检查文件权限';
    }
}

// 如果未登录，显示登录表单
if (!$loggedIn) {
    echo '<!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>管理员登录</title>
        <style>
                        body {
                font-family: Arial, sans-serif;
                background: linear-gradient(135deg, #8e44ad 0%, #9b59b6 100%);
                display: flex;
                justify-content: center;
                align-items: center;
                height: 100vh;
                margin: 0;
            }
            .container {
                text-align: center;
                background-color: rgba(255, 255, 255, 0.9);
                padding: 30px;
                border-radius: 12px;
                box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
                width: 350px;
                backdrop-filter: blur(8px);
                border: 1px solid rgba(255, 255, 255, 0.18);
            }
            h1 {
                color: #5b2c6f;
                margin-bottom: 20px;
            }
            input[type="password"] {
                padding: 12px;
                border: 1px solid #ddd;
                border-radius: 6px;
                font-size: 16px;
                margin-bottom: 15px;
                width: 100%;
                box-sizing: border-box;
                background-color: rgba(255, 255, 255, 0.8);
            }
            input[type="submit"] {
                background: linear-gradient(to right, #9b59b6, #8e44ad);
                color: white;
                border: none;
                padding: 12px 20px;
                border-radius: 6px;
                cursor: pointer;
                font-size: 16px;
                width: 100%;
                transition: all 0.3s ease;
                box-shadow: 0 4px 15px rgba(142, 68, 173, 0.4);
            }
            input[type="submit"]:hover {
                background: linear-gradient(to right, #8e44ad, #9b59b6);
                transform: translateY(-2px);
                box-shadow: 0 6px 20px rgba(142, 68, 173, 0.6);
            }
            .error {
                color: #ff6b6b;
                margin-bottom: 15px;
                text-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
            }
        </style>
    </head>
    <body>
        <div class="container">
            <h1>Best Image API管理登录</h1>
            '.(!empty($loginError) ? '<div class="error">'.$loginError.'</div>' : '').'<form method="post">
                请输入密码: <input type="password" name="password" />
                <input type="submit" value="登录" />
            </form>
        </div>
    </body>
    </html>';
    exit;
}

// 以下是管理界面内容
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Best Image API Admin</title>
    <link rel="stylesheet" href="admin.css">
        
  
</head>
<body>
    <div class="container">
        <div class="logout-link">
       
        </div>
        
        <h1>Best Image API管理员后台</h1>
        
        <div class="success-message" style="display: <?php echo isset($configSaved) ? 'block' : 'none'; ?>">
            配置已成功保存！
        </div>
        <div class="error" style="color: red; margin-bottom: 15px; display: <?php echo isset($configError) ? 'block' : 'none'; ?>">
            <?php echo isset($configError) ? $configError : ''; ?>
        </div>
        
        <form method="post">
            <div class="section">
                <h2 class="section-title">系统运行模式</h2>
                <div class="checkbox-group">
                    <label>
                        <input type="checkbox" id="maintenanceMode" name="maintenanceMode" <?php echo (isset($_POST['maintenanceMode']) || (isset($config['maintenanceMode']) && $config['maintenanceMode'])) ? 'checked' : ''; ?>> 维护模式
                    </label>
                </div>
                <div class="checkbox-group">
                    <label>
                        <input type="checkbox" id="smartFormatSelection" name="smartFormatSelection" <?php echo (isset($_POST['smartFormatSelection']) || !isset($config['smartFormatSelection']) || $config['smartFormatSelection']) ? 'checked' : ''; ?>> 智能图片格式选择
                    </label>
                </div>
                <div class="checkbox-group">
                    <label>
                        <input type="checkbox" id="rateLimitEnabled" name="rateLimitEnabled" <?php echo (isset($_POST['rateLimitEnabled']) || !isset($config['rateLimitEnabled']) || $config['rateLimitEnabled']) ? 'checked' : ''; ?>> 访问频率限制
                    </label>
                </div>
                <div class="checkbox-group">
                    <label>
                        <input type="checkbox" id="hotlinkProtection" name="hotlinkProtection" <?php echo (isset($_POST['hotlinkProtection']) || !isset($config['hotlinkProtection']) || $config['hotlinkProtection']) ? 'checked' : ''; ?>> 防盗链保护
                    </label>
                </div>
                <div class="checkbox-group">
                    <label>
                        <input type="checkbox" id="nginxCacheEnabled" name="nginxCacheEnabled" <?php echo (isset($_POST['nginxCacheEnabled']) || !isset($config['nginxCacheEnabled']) || $config['nginxCacheEnabled']) ? 'checked' : ''; ?>> Nginx图片缓存
                    </label>
                    <small style="display: block; margin-left: 25px; color: #666;">启用后将使用Nginx缓存图片，提高访问速度和减轻服务器负载</small>
                </div>
                <div class="checkbox-group">
                    <label>
                        <input type="checkbox" id="redisEnabled" name="redisEnabled" <?php echo (isset($_POST['redisEnabled']) || (isset($config['redisEnabled']) && $config['redisEnabled'])) ? 'checked' : ''; ?>> Redis缓存
                    </label>
                    <small style="display: block; margin-left: 25px; color: #666;">启用后将使用Redis缓存图片和数据，提高访问速度和系统性能</small>
                </div>
                <label for="redirectMode">重定向模式:</label>
                <select id="redirectMode" name="redirectMode">
                    <option value="1" selected>1-标准模式</option>
                    <option value="2">2-链接模式</option>
                </select>
            </div>
            
            <div class="section">
                <h2 class="section-title">访问频率限制</h2>
                <label for="rateLimitThreshold">每分钟单IP最大请求数限制:</label>
                <input type="number" id="rateLimitThreshold" name="rateLimitThreshold" value="<?php echo isset($_POST['rateLimitThreshold']) ? htmlspecialchars($_POST['rateLimitThreshold']) : (isset($config['rateLimitThreshold']) ? htmlspecialchars($config['rateLimitThreshold']) : '1'); ?>" min="1">
            </div>
           
            
            <div class="section">
               <h2 class="section-title">支持的图片格式</h2>
                
                
                <label for="blacklistFile">IP黑名单文件路径:</label>
                <input type="text" id="blacklistFile" name="blacklistFile" value="blacklist.txt">
                
                <label for="whitelistFile">IP白名单文件路径:</label>
                <input type="text" id="whitelistFile" name="whitelistFile" value="whitelist.txt">
                
                <label for="rateLimitFile">访问频率记录文件路径:</label>
                <input type="text" id="rateLimitFile" name="rateLimitFile" value="rate_limit.txt">
            </div>
            
            <div class="section">
                <h2 class="section-title">防盗链允许域名</h2>
                <div id="allowedDomains">
                    <?php if (isset($config['allowedDomains']) && is_array($config['allowedDomains']) && !empty($config['allowedDomains'])): ?>
                        <?php foreach ($config['allowedDomains'] as $domain): ?>
                            <div class="domain-entry">
                                <input type="text" class="domain" name="domain[]" value="<?php echo htmlspecialchars($domain); ?>">
                                <button type="button" class="remove-domain">删除</button>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div class="domain-entry">
                            <input type="text" class="domain" name="domain[]" value="example.com">
                            <button type="button" class="remove-domain">删除</button>
                        </div>
                        <div class="domain-entry">
                            <input type="text" class="domain" name="domain[]" value="yourdomain.com">
                            <button type="button" class="remove-domain">删除</button>
                        </div>
                    <?php endif; ?>
                </div>
                <button type="button" id="addDomain">添加域名</button>
            </div>
            
            <div class="section">
                <h2 class="section-title">Redis连接配置</h2>
                <label for="redisHost">Redis主机地址:</label>
                <input type="text" id="redisHost" name="redisHost" value="<?php echo isset($config['redisHost']) ? htmlspecialchars($config['redisHost']) : 'localhost'; ?>">
                
                <label for="redisPort">Redis端口:</label>
                <input type="number" id="redisPort" name="redisPort" value="<?php echo isset($config['redisPort']) ? htmlspecialchars($config['redisPort']) : '6379'; ?>" min="1" max="65535">
                
                <label for="redisPassword">Redis密码 (如果有):</label>
                <input type="password" id="redisPassword" name="redisPassword" value="<?php echo isset($config['redisPassword']) ? htmlspecialchars($config['redisPassword']) : ''; ?>">
                
                <label for="redisDatabase">Redis数据库编号:</label>
                <input type="number" id="redisDatabase" name="redisDatabase" value="<?php echo isset($config['redisDatabase']) ? htmlspecialchars($config['redisDatabase']) : '0'; ?>" min="0" max="15">
                
                <small style="display: block; margin-top: 10px; color: #666;">注意：只有在启用Redis缓存选项后，以上配置才会生效</small>
            </div>
            
            <button type="submit" name="save_config" id="saveConfig">保存所有配置</button>
            
            
            <div class="section">
                <h2 class="section-title">黑名单管理</h2>
                <div class="success-message" style="display: <?php echo isset($blacklistSaved) ? 'block' : 'none'; ?>">
                    黑名单文件已成功保存！
                </div>
                <div class="error" style="color: red; margin-bottom: 15px; display: <?php echo isset($blacklistError) ? 'block' : 'none'; ?>">
                    <?php echo isset($blacklistError) ? $blacklistError : ''; ?>
                </div>
                <form method="post">
                    <input type="hidden" name="blacklist_file_path" value="<?php echo isset($_POST['blacklistFile']) ? $_POST['blacklistFile'] : 'blacklist.txt'; ?>">
                    <label for="blacklist_content">黑名单内容 (每行一个IP):</label>
                    <textarea id="blacklist_content" name="blacklist_content" rows="10" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box;"><?php 
                        $blacklistFilePath = isset($_POST['blacklistFile']) ? $_POST['blacklistFile'] : 'blacklist.txt';
                        if (file_exists($blacklistFilePath)) {
                            echo htmlspecialchars(file_get_contents($blacklistFilePath));
                        }
                    ?></textarea>
                    <div style="margin-top: 10px;">
                        <button type="submit" name="save_blacklist">保存黑名单</button>
                        <button type="button" onclick="document.getElementById('blacklist_content').value = '';" style="background-color: #ff4d4d; color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer; margin-left: 10px;">清空黑名单</button>
                    </div>
                </form>
            </div>
            
            <div class="section">
                <h2 class="section-title">白名单管理</h2>
                <div class="success-message" style="display: <?php echo isset($whitelistSaved) ? 'block' : 'none'; ?>">
                    白名单文件已成功保存！
                </div>
                <div class="error" style="color: red; margin-bottom: 15px; display: <?php echo isset($whitelistError) ? 'block' : 'none'; ?>">
                    <?php echo isset($whitelistError) ? $whitelistError : ''; ?>
                </div>
                <form method="post">
                    <input type="hidden" name="whitelist_file_path" value="<?php echo isset($_POST['whitelistFile']) ? $_POST['whitelistFile'] : 'whitelist.txt'; ?>">
                    <label for="whitelist_content">白名单内容 (每行一个IP):</label>
                    <textarea id="whitelist_content" name="whitelist_content" rows="10" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box;"><?php 
                        $whitelistFilePath = isset($_POST['whitelistFile']) ? $_POST['whitelistFile'] : 'whitelist.txt';
                        if (file_exists($whitelistFilePath)) {
                            echo htmlspecialchars(file_get_contents($whitelistFilePath));
                        }
                    ?></textarea>
                    <div style="margin-top: 10px;">
                        <button type="submit" name="save_whitelist">保存白名单</button>
                        <button type="button" onclick="document.getElementById('whitelist_content').value = '';" style="background-color: #ff4d4d; color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer; margin-left: 10px;">清空白名单</button>
                    </div>
                </form>
            </div>
            
            <div class="section">
                <h2 class="section-title">访问日志管理</h2>
                <div class="success-message" style="display: <?php echo isset($ratelogSaved) ? 'block' : 'none'; ?>">
                    访问日志文件已成功保存！
                </div>
                <div class="error" style="color: red; margin-bottom: 15px; display: <?php echo isset($ratelogError) ? 'block' : 'none'; ?>">
                    <?php echo isset($ratelogError) ? $ratelogError : ''; ?>
                </div>
                <form method="post">
                    <input type="hidden" name="ratelog_file_path" value="<?php echo isset($_POST['rateLimitFile']) ? $_POST['rateLimitFile'] : 'rate_limit.txt'; ?>">
                    <label for="ratelog_content">访问日志内容:</label>
                    <textarea id="ratelog_content" name="ratelog_content" rows="15" style="width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box;"><?php 
                        $ratelogFilePath = isset($_POST['rateLimitFile']) ? $_POST['rateLimitFile'] : 'rate_limit.txt';
                        if (file_exists($ratelogFilePath)) {
                            echo htmlspecialchars(file_get_contents($ratelogFilePath));
                        }
                    ?></textarea>
                    <div style="margin-top: 10px;">
                        <button type="submit" name="save_ratelog">保存访问日志</button>
                        <button type="button" onclick="document.getElementById('ratelog_content').value = '';" style="background-color: #ff4d4d; color: white; border: none; padding: 10px 20px; border-radius: 4px; cursor: pointer; margin-left: 10px;">清空访问日志</button>
                    </div>
                </form>
            </div>
            
            
           
              
           
        </form>
    </div>

    <script>
        
        
        // 添加域名
        document.getElementById('addDomain').addEventListener('click', function() {
            const domainsContainer = document.getElementById('allowedDomains');
            const newDomainEntry = document.createElement('div');
            newDomainEntry.className = 'domain-entry';
            newDomainEntry.innerHTML = `
                <input type="text" class="domain" name="domain[]" value="">
                <button type="button" class="remove-domain">删除</button>
            `;
            domainsContainer.appendChild(newDomainEntry);
            
            // 为新添加的删除按钮绑定事件
            newDomainEntry.querySelector('.remove-domain').addEventListener('click', function() {
                domainsContainer.removeChild(newDomainEntry);
                updateConfigPreview();
            });
        });
        
        // 为已有的删除按钮绑定事件
        document.querySelectorAll('.remove-domain').forEach(button => {
            button.addEventListener('click', function() {
                const domainEntry = this.parentNode;
                domainEntry.parentNode.removeChild(domainEntry);
                updateConfigPreview();
            });
        });
        
        // 更新配置预览
        function updateConfigPreview() {
            const config = {
                maintenanceMode: document.getElementById('maintenanceMode').checked,
                smartFormatSelection: document.getElementById('smartFormatSelection').checked,
                rateLimitEnabled: document.getElementById('rateLimitEnabled').checked,
                hotlinkProtection: document.getElementById('hotlinkProtection').checked,
                nginxCacheEnabled: document.getElementById('nginxCacheEnabled').checked,
                redisEnabled: document.getElementById('redisEnabled').checked,
                redirectMode: document.getElementById('redirectMode').value,
                rateLimitThreshold: document.getElementById('rateLimitThreshold').value,
                // 移除对不存在元素的引用
                // supportedFormats: Array.from(document.querySelectorAll('input[name="format[]"]:checked')).map(el => el.value),
                // imageDir: document.getElementById('imageDir').value,
                blacklistFile: document.getElementById('blacklistFile').value,
                whitelistFile: document.getElementById('whitelistFile').value,
                rateLimitFile: document.getElementById('rateLimitFile').value,
                allowedDomains: Array.from(document.querySelectorAll('.domain')).map(el => el.value),
                redisHost: document.getElementById('redisHost').value,
                redisPort: document.getElementById('redisPort').value,
                redisPassword: document.getElementById('redisPassword').value,
                redisDatabase: document.getElementById('redisDatabase').value
            };
            
            // 如果configPreview元素不存在，则不更新
            const configPreviewElement = document.getElementById('configPreview');
            if (configPreviewElement) {
                configPreviewElement.textContent = JSON.stringify(config, null, 2);
            }
        }
        
        // 初始化配置预览
        updateConfigPreview();
        
        // 为所有输入元素添加事件监听，以便在更改时更新预览
        document.querySelectorAll('input, select').forEach(el => {
            el.addEventListener('change', updateConfigPreview);
        });
        
        // 文件路径变更时更新对应的文件内容
        document.getElementById('blacklistFile').addEventListener('change', function() {
            const filePath = this.value;
            document.querySelector('input[name="blacklist_file_path"]').value = filePath;
            // 使用AJAX请求获取文件内容
            fetch('index.php?action=get_file_content&file=' + encodeURIComponent(filePath))
                .then(response => response.text())
                .then(content => {
                    document.getElementById('blacklist_content').value = content;
                })
                .catch(error => {
                    console.error('获取文件内容失败:', error);
                });
        });
        
        document.getElementById('whitelistFile').addEventListener('change', function() {
            const filePath = this.value;
            document.querySelector('input[name="whitelist_file_path"]').value = filePath;
            // 使用AJAX请求获取文件内容
            fetch('index.php?action=get_file_content&file=' + encodeURIComponent(filePath))
                .then(response => response.text())
                .then(content => {
                    document.getElementById('whitelist_content').value = content;
                })
                .catch(error => {
                    console.error('获取文件内容失败:', error);
                });
        });
        
        document.getElementById('rateLimitFile').addEventListener('change', function() {
            const filePath = this.value;
            document.querySelector('input[name="ratelog_file_path"]').value = filePath;
            // 使用AJAX请求获取文件内容
            fetch('index.php?action=get_file_content&file=' + encodeURIComponent(filePath))
                .then(response => response.text())
                .then(content => {
                    document.getElementById('ratelog_content').value = content;
                })
                .catch(error => {
                    console.error('获取文件内容失败:', error);
                });
        });
    </script>
</body>
</html>


